package com.liaowei.novel.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.liaowei.novel.R;
import com.liaowei.novel.activity.NovelDetailActivity;
import com.liaowei.novel.activity.ReadActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookshelfFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookshelfFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ListView shelf_lv;
    private SQLiteDatabase db;
    private String[] from = {"id", "coverImage", "name","chapterName"};
    private int[] to = {R.id.shelf_id,R.id.shelf_cover_image, R.id.shelf_name,R.id.shelf_chapter};
    private Cursor cursor;
    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;

    public BookshelfFragment() {
        // Required empty public constructor
    }
    public BookshelfFragment(SQLiteDatabase db) {
        this.db = db;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BookshelfFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookshelfFragment newInstance(String param1, String param2) {
        BookshelfFragment fragment = new BookshelfFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bookshelf, container, false);
        shelf_lv = view.findViewById(R.id.shelf_lv);
        SimpleAdapter adapter = new SimpleAdapter(getContext(), getData(), R.layout.shelf_item, this.from, this.to);
        shelf_lv.setAdapter(adapter);

        return view;
    }

    public List<Map<String, Object>> getData(){
        String sql = "select n.id,n.name,n.coverImage,ch.title\n" +
                "from novel n\n" +
                "join bookshelf bs on bs.novel_id = n.id and bs.user_id = 8\n" +
                "left join history h on h.novel_id = n.id\n" +
                "left join chapter ch on ch.id = h.chapter_id\n" +
                "order by h.create_time desc";
        cursor = db.rawQuery(sql, null);
        List<Map<String, Object>> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String coverImage = cursor.getString(cursor.getColumnIndex("coverImage"));
            String chapterName = cursor.getString(cursor.getColumnIndex("title"));
            if (chapterName == null){
                chapterName = "暂无记录";
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("coverImage", coverImage);
            map.put("name", name);
            map.put("chapterName", chapterName);
            list.add(map);
        }
        return list;
    }


    class SimpleAdapter extends android.widget.SimpleAdapter {
        public SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            Map<String, Object> item = (Map<String, Object>) getItem(position);
            String coverImage = (String) item.get("coverImage");
            ImageView iv = v.findViewById(R.id.shelf_cover_image);
            Glide.with(v).load(coverImage).into(iv);

            LinearLayout line = v.findViewById(R.id.shelf_item);

            line.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    TextView tv_id = v.findViewById(R.id.shelf_id);
                    String strId = tv_id.getText().toString();
                    int id = Integer.parseInt(strId);
                    Intent intent = new Intent(getActivity(), ReadActivity.class);
                    intent.putExtra("novelId",id);
                    intent.putExtra("userId",8);
                    startActivity(intent);
                }
            });

            return v;
        }
    }

}